package com.estronger.shopmanage.ui.aftermarket;

import android.content.Intent;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.BeanBase;
import com.estronger.shopmanage.bean.BeanImage;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.aftermarket.bean.AftermarketDetailBean;
import com.estronger.shopmanage.ui.aftermarket.bean.AftermarketItem;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.AddPhotosView;
import com.estronger.shopmanage.view.AddVideoView;
import com.estronger.shopmanage.view.AppDialog;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.soonfor.evaluate.tools.ImageUtils;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CompletedConfirmActivity extends BaseActivity implements AddPhotosView.EventListener{


    @BindView(R.id.result_build_name)
    TextView tv_client;
    @BindView(R.id.result_build_date_real)
    TextView tv_actual_time;
    @BindView(R.id.view_build_before)
    AddPhotosView view_build_before;
    @BindView(R.id.view_build_after)
    AddPhotosView view_build_after;//安装前中后
    @BindView(R.id.view_before_video)
    AddVideoView addBeforeVideoView;//安装前视频
    @BindView(R.id.view_after_video)
    AddVideoView addAfterVideo;//安装后视频

    final int CODE_BUILDING_BEFORE = 3000,CODE_BEFORE_VIDEO = 4000, CODE_BUILDING_AFTER = 5000,CODE_AFTER_VIDEO = 6000;
    private boolean beforeUploadFn = false, afterUploadFn = false,beforVideoUploaded = false,afterVideoUploaded = false;
    private ArrayList<String> beforePaths = new ArrayList<String>();//安装前的图片
    private ArrayList<String> afterPaths = new ArrayList<String>();//安装后的图片
    private ArrayList<String> beforeVideoPaths = new ArrayList<String>();//安装前的视频
    private ArrayList<String> afterVideoPaths = new ArrayList<String>();//安装后的视频

    @BindView(R.id.build_input_remark)
    EditText editText;

    AftermarketItem detainInfoBean;

    @Override
    protected void initView() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = View.inflate(this, R.layout.activity_app_completed_confirm_layout,null);
        setContentView(view);

        ButterKnife.bind(this,view);
        initUI();
        requestDetail();
    }

    void initUI(){
        view_build_before.initView(this, CODE_BUILDING_BEFORE, this);
        view_build_before.initData("完工前的图片", 99);
        view_build_after.initView(this, CODE_BUILDING_AFTER, this);
        view_build_after.initData("完工后的图片", 99);
        addBeforeVideoView.initView(this,CODE_BEFORE_VIDEO,this);
        addBeforeVideoView.initData("完工前的视频",99);
        addAfterVideo.initView(this,CODE_AFTER_VIDEO,this);
        addAfterVideo.initData("完工后的视频",99);
    }

    // 时间选择
    public void showPicker(View view) {
        AppDialog.createPicker(this, tv_actual_time).show();
    }

    void onBindData(){
        tv_client.setText(detainInfoBean.getFcstname());
        tv_actual_time.setText(TimeUtils.formatTime(System.currentTimeMillis(), ""));
    }

    void requestDetail(){
        String taskId = getIntent().getStringExtra("taskId");
        RequestParams params = new RequestParams();
        params.addBodyParameter("sf_action", "claimgettaskdetail");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("taskid", taskId);
        showDialog("获取任务详情中",true);
        connect(params, NetManager.AFTERMARKET_DETAIL);
    }


    @Override
    protected void onNetErorr(int code, String msg) {
        super.onNetErorr(code, msg);
        if (code == NetManager.AFTERMARKET_CONFIR_COM){
            closeLoadDialog();
        }
    }

    @Override
    protected void onNetSuccess(int code, String result) {
        super.onNetSuccess(code, result);
        if (code == NetManager.AFTERMARKET_DETAIL){
            AftermarketDetailBean detailBean = gson.fromJson(result,AftermarketDetailBean.class);
            detainInfoBean = detailBean.getData();
            onBindData();
            Log.e("AppointmentSureActivity",result);
        }else if (code == NetManager.AFTERMARKET_CONFIR_COM){
            BeanBase bean = gson.fromJson(result, BeanBase.class);
            if (bean.success) {
                com.estronger.shopmanage.utils.Toast.show(this, "提交成功", 2000);
                setResult(AftermarketActivity.REFLESH_DATA);
                finish();
            } else {
                com.estronger.shopmanage.utils.Toast.show(this, bean.msg, 2000);
            }
            closeLoadDialog();
        }
    }


    @Override
    protected void onNetIMGSuccess(int code, String result) {
        if (code == CODE_BUILDING_BEFORE) view_build_before.uploadSuccess(code,result);
        else if (code == CODE_BUILDING_AFTER) view_build_after.uploadSuccess(code,result);
        else if (code == CODE_BEFORE_VIDEO) addBeforeVideoView.uploadSuccess(code,result);
        else if (code == CODE_AFTER_VIDEO) addAfterVideo.uploadSuccess(code,result);

    }

    void uploadImageAndVideo(){

        beforePaths.clear();
        beforeVideoPaths.clear();
        afterPaths.clear();
        afterVideoPaths.clear();

        beforeUploadFn = false;
        afterUploadFn = false;
        beforVideoUploaded = false;
        afterVideoUploaded = false;


        if (view_build_before.getFileList().size() == 0
                && view_build_after.getFileList().size() == 0
                && addAfterVideo.getFileList().size() == 0
                && addBeforeVideoView.getFileList().size() == 0){
            saveData();
            return;
        }
        if (view_build_before.getFileList().size() == 0){
            beforeUploadFn = true;
        }else {
            view_build_before.postPics();
        }
        if (view_build_after.getFileList().size() == 0){
            afterUploadFn = true;
        }else {
            view_build_after.postPics();
        }
        if (addBeforeVideoView.getFileList().size() == 0){
            beforVideoUploaded = true;
        }else {
            addBeforeVideoView.postPics();
        }
        if (addAfterVideo.getFileList().size() == 0){
            afterVideoUploaded = true;
        }else {
            addAfterVideo.postPics();
        }
    }

    void saveData(){

        String taskId = getIntent().getStringExtra("taskId");
        List<Map<String,String>> imageItems = new ArrayList<>();
        for (String url : beforePaths){
            Map<String,String> item = new HashMap<>();
            item.put("phasetype","0");
            item.put("taskid",taskId);
            item.put("path",url);
            item.put("filename",System.currentTimeMillis() + ".jpg");
            item.put("type","0");
            item.put("videoimgpath","");
            imageItems.add(item);
        }
        for (String url : beforeVideoPaths){
            Map<String,String> item = new HashMap<>();
            item.put("phasetype","0");
            item.put("taskid",taskId);
            item.put("path","");
            item.put("filename",System.currentTimeMillis() + ".mp4");
            item.put("type","1");
            item.put("videoimgpath",url);
            imageItems.add(item);
        }
        for (String url : afterPaths){
            Map<String,String> item = new HashMap<>();
            item.put("phasetype","1");
            item.put("taskid",taskId);
            item.put("path",url);
            item.put("filename",System.currentTimeMillis() + ".jpg");
            item.put("type","0");
            item.put("videoimgpath","");
            imageItems.add(item);
        }
        for (String url : afterVideoPaths){
            Map<String,String> item = new HashMap<>();
            item.put("phasetype","1");
            item.put("taskid",taskId);
            item.put("path","");
            item.put("filename",System.currentTimeMillis() + ".mp4");
            item.put("type","1");
            item.put("videoimgpath",url);
            imageItems.add(item);
        }


        String desCotnent = editText.getText().toString().trim();

        Gson gson = new Gson();

        String time = tv_actual_time.getText().toString().trim();
        RequestParams params = new RequestParams();
        params.addBodyParameter("imgitem", gson.toJson(imageItems));
        params.addBodyParameter("sf_action", "claimgtaskfinish");
        params.addBodyParameter("usercode", MyApplication.getUserCode());
        params.addBodyParameter("taskid", taskId);
        params.addBodyParameter("acttime",time);
        params.addBodyParameter("finishdesc",desCotnent);
        showDialog("数据提交中...", true);
        connect(params, NetManager.AFTERMARKET_CONFIR_COM);
    }

    /*
     * 保存
     * */
    public void save(View view) {

        if (view_build_after.getFileList().size() == 0){
            Toast.show(this,"请上传完工后的图片",Toast.LENGTH_LONG);
            return;
        }

        showDialog("提交数据中...", false);
        uploadImageAndVideo();
    }


    /**
     * 判断容器里的图片是否达到最高选择数量
     */
    private boolean isOutOfLimit(int code) {
        // 下面开始判断整体容器里的图片是否达到最高选择数量
        if (code == CODE_BUILDING_BEFORE) {
            if (view_build_before.getPhotosCount() >= 99) {
                com.estronger.shopmanage.utils.Toast.show(this, "安装前的图片最多可上传99张", 2000);
                return true;
            }
        }  else  {
            if (view_build_after.getPhotosCount() >= 99) {
                Toast.show(this, "安装后的图片最多可上传99张", 2000);
                return true;
            }
            return false;
        }
        return false;
    }

    @Override
    public void openAlbum(int id) {
        if (isOutOfLimit(id)) return;
        List<LocalMedia> lastMedias = new ArrayList<>();
        if (id == CODE_BUILDING_BEFORE) {
            lastMedias.addAll(view_build_before.getFileList());
        }else {
            lastMedias.addAll(view_build_after.getFileList());
        }
        ImageUtils.pictureSelect(this, PictureConfig.MULTIPLE, 99, lastMedias, id + 1);
    }

    @Override
    public boolean openCamera(int id) {
// 当达到最高图片数量时直接返回
        return isOutOfLimit(id);
//        if (isOutOfLimit(id))
//            return;
//        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//        startActivityForResult(intent, id + 2);
    }

    @Override
    public void uploadPic(RequestParams params, int requestCode) {
        updateIMG(params, requestCode);
    }

    @Override
    public void uploadVideoByParam(RequestParams params, int code) {
        uploadVideo(params,code);
    }

    @Override
    public void afterUploadVideos(boolean isSuccess, ArrayList<BeanImage> urls, int requestCode) {

    }

    @Override
    public void afterUploadPics(boolean isSuccess, ArrayList<String> urls, int requestCode) {
        if (isSuccess) {
            if (requestCode == CODE_BUILDING_BEFORE) {
                beforeUploadFn = true;
                beforePaths.addAll(urls);
            }else if (requestCode == CODE_BEFORE_VIDEO){
                beforVideoUploaded = true;
                beforeVideoPaths.addAll(urls);
            }else if (requestCode == CODE_AFTER_VIDEO){
                afterVideoUploaded = true;
                afterVideoPaths.addAll(urls);
            }else{
                afterUploadFn = true;
                afterPaths.addAll(urls);
            }
            if (afterUploadFn
                    && beforeUploadFn
                    && beforVideoUploaded
                    && afterVideoUploaded){
                saveData();
            }
        }else {
            closeLoadDialog();
        }
    }

    @Override
    public void showLoadDialog() {
        showDialog("上传图片中...", false);
    }

    @Override
    public void closeLoadDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (Math.abs(requestCode - CODE_BUILDING_BEFORE) < 4) {//安装前
            view_build_before.onActivityResult(requestCode, data);
        }else if (Math.abs(requestCode - CODE_BUILDING_AFTER) < 4){//安装后
            view_build_after.onActivityResult(requestCode, data);
        }else if (Math.abs(requestCode - CODE_BEFORE_VIDEO) < 4){
            addBeforeVideoView.onActivityResult(requestCode,data);
        }else if (Math.abs(requestCode - CODE_AFTER_VIDEO) < 4){
            addAfterVideo.onActivityResult(requestCode,data);
        }
    }
}
